﻿using SHTools;
using UnityEditor;
using UnityEngine;
using UnityEngine.Rendering;

// 创建一个自定义编辑器类，用于编辑 MyScriptableObject
[CustomEditor(typeof(DayNightData))]
public class DayNightDataEditor : Editor
{
    // 立方体贴图
    static Cubemap cubemap;
    private DayNightData  self;

    private void OnEnable()
    {
        // 获取 target 并将其转换为 MyScriptableObject 类型
        self = (DayNightData )target;
    }

    // 更新反射数据
    public void UpdateReflect( )
    {
        // 如果当前昼夜数据的环境色类型是天空盒
        if (self.ambientType == AmbientType.SkyBox)
        {
            // 相机对象
            Camera refCam;
            // 创建一个用于渲染立方体贴图的相机对象
            GameObject camObj = new GameObject("CubemapCamera");
            refCam = camObj.AddComponent<Camera>();
            // 隐藏相机对象，不保存到场景中
            refCam.hideFlags = HideFlags.DontSave;
            // 相机不渲染任何层
            refCam.cullingMask = 0;
            // 如果立方体贴图为空，则创建一个新的立方体贴图
            if (null == cubemap)
                cubemap = new Cubemap(128, TextureFormat.RGB24, true);
            // 保存当前的天空盒材质
            var old = RenderSettings.skybox;
            // 设置渲染用的天空盒材质为当前昼夜数据的材质
            RenderSettings.skybox = self.mat;
            // 渲染立方体贴图
            refCam.RenderToCubemap(cubemap);
            // 恢复原来的天空盒材质
            RenderSettings.skybox = old;
            // 销毁相机对象
            GameObject.DestroyImmediate(camObj);
            // 将立方体贴图投影到球谐函数中
            SphericalHarmonicsL2 sh = RawSphericalHarmonicsL2.ProjectCubemapIntoSHMonteCarlo(cubemap, 256, true).AsUnityConvention();
            // 将球谐函数结果赋值给当前昼夜数据
            self.sh = sh;

            // 如果当前昼夜数据的系数数组为空，则创建一个新的数组
            if (self.coefficients.Length == 0 || self.coefficients == null)
            {
                self.coefficients = new float[27];
            }
            // 将球谐函数的系数赋值给当前昼夜数据的系数数组
            for (int c = 0; c < 3; c++)             // R, G, B
            {
                for (int i = 0; i < 9; i++)         // 9 coefficients
                {
                    int id = i * 3 + c;             // 顺序不变
                    float f = sh[c, i];             // 正确顺序是：sh[color, coefficient]
                    self.coefficients[id] = f;
                }
            }
            // 在编辑器中标记该对象为已修改
#if UNITY_EDITOR
            EditorUtility.SetDirty(this);
#endif
        }
    }
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();

        if (self.needBake)
        {
            self.needBake = false;
            UpdateReflect();
        }
		
    }
}
#if UNITY_EDITOR
 

[CustomEditor(typeof(DayNightCurve))]
public class DayNightCurveEditor : Editor
{
    private SerializedProperty dayNightDatas;

    private void OnEnable()
    {
        dayNightDatas = serializedObject.FindProperty("dayNightDatas");
    }

    public override void OnInspectorGUI()
    {
        serializedObject.Update();

        EditorGUILayout.LabelField("昼夜曲线数据", EditorStyles.boldLabel);

        for (int i = 0; i < dayNightDatas.arraySize; i++)
        {
            EditorGUILayout.BeginHorizontal();

            // 绘制数组元素
            EditorGUILayout.PropertyField(dayNightDatas.GetArrayElementAtIndex(i), new GUIContent($"元素 {i}"), true);

            // 删除按钮
            if (GUILayout.Button("-", GUILayout.Width(20)))
            {
                dayNightDatas.DeleteArrayElementAtIndex(i);
                serializedObject.ApplyModifiedProperties();
                break; // 退出循环防止索引越界
            }

            // 复制插入按钮
            if (GUILayout.Button("+", GUILayout.Width(20)))
            {
                dayNightDatas.InsertArrayElementAtIndex(i);
                CopyElementValues(i, i + 1);
                serializedObject.ApplyModifiedProperties();
                break; // 退出循环防止索引越界
            }

            EditorGUILayout.EndHorizontal();
        }

        // 添加新元素按钮
        if (GUILayout.Button("添加新元素"))
        {
            dayNightDatas.arraySize++;
        }

        serializedObject.ApplyModifiedProperties();
    }

    private void CopyElementValues(int sourceIndex, int targetIndex)
    {
        SerializedProperty source = dayNightDatas.GetArrayElementAtIndex(sourceIndex);
        SerializedProperty target = dayNightDatas.GetArrayElementAtIndex(targetIndex);

        // 手动复制所有序列化字段
        CopyPropertyFields(source, target);
    }

    private void CopyPropertyFields(SerializedProperty source, SerializedProperty target)
    {
        // 遍历所有子属性进行复制
        SerializedProperty iterator = source.Copy();
        bool enterChildren = true;
        while (iterator.NextVisible(enterChildren))
        {
            enterChildren = false;
            string propertyPath = iterator.propertyPath;
            SerializedProperty targetProperty = target.FindPropertyRelative(propertyPath);

            if (targetProperty != null && targetProperty.propertyType == iterator.propertyType)
            {
                EditorJsonUtility.FromJsonOverwrite(EditorJsonUtility.ToJson(iterator), targetProperty);
            }
        }
    }
}
#endif
/*    public class DayNightCurve : ScriptableObject
{
    public List<DataNightContain> dayNightDatas = new List<DataNightContain>();
}*/
